package ex3.taskqueue;

import ex3.executor.Executor;

public class ExecuteTask implements Runnable {
	
	public ExecuteTask(Executor e, char op, int opID, int op1, int op2, OpQueue caller){
		task = new TaskInfo(opID, op, op1, op2);
		executor = e;
		callerQueue = caller;
	}
	
	//	Runnning the executor and printing result or returning the task to the front of the opQueue
	public void run() {
		String res = null;
		try {
			res = executor.execute(task.op, task.op1, task.op2);
		}
		catch (Exception e) {
			//	Adding a thread to prevent collapse
			TaskQueueImpl.taskQueue.AddTask(task.op, task.taskID, task.op1, task.op2, true);
		}
		
		if (res == null || res.compareTo("EXECUTOR_ERROR") == 0){
			//	Error. Return to taskQueue
			TaskQueueImpl.taskQueue.AddTask(task.op, task.taskID, task.op1, task.op2, true);	
		}
		else{
			//	Success - print to file
			TaskQueueImpl.taskQueue.WriteToOutputFile(task.taskID + ":" + res);
		}
		
		//	Destroying the thread and notifing the caller
		TaskQueueImpl.taskQueue.DestroyThread();
		callerQueue.FinishedATask();
	}

	private TaskInfo task;
	private Executor executor;
	private OpQueue callerQueue;
}
